import { defineStore } from 'pinia';
import { AppRouteRecordRaw, Menu } from '/@/router/types';
import { SaaSUserMenuParams } from '/@/api/sys/model/menuModel';
import { useMessage } from '/@/hooks/web/useMessage';
import { useI18n } from '/@/hooks/web/useI18n';
import { SaaSPageEnum } from '/@/enums/pageEnum';
import { store } from '/@/store';
import { useAppSettingStoreWithOut } from './appSetting';
import { getSaaSAccessibleMenu } from '/@/api/sys/menu';
import { flatMultiLevelRoutes, replaceList, transformObjToRoute } from '/@/router/helper/routeHelper';
import { transformRouteToMenu } from '/@/router/helper/menuHelper';
import { loginSaaSApi } from '/@/api/sys/user';
import { useUserStoreWithout } from './user';
import { SaaSLoginParams } from '/@/api/sys/model/userModel';
import { PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';
import { hashPowerList } from '/@/utils/permission';
import { getPermission } from '../../api/sys/menu';
import { parseUrl } from '../../utils/sso/utils';
import { getToken } from '../../hooks/globVar/index';
import { importFrontendRoutes, userInfoRoute } from '../../router/helper/routeHelper';
/* eslint-disable */
interface PermissionState {
  backMenuList: Menu[];
  isDynamicAddedRoute: boolean;
  hashPower: Recordable;
}

export const usePermissionStore = defineStore({
  id: 'permission',
  state: (): PermissionState => ({
    backMenuList: [],
    isDynamicAddedRoute: false,
    hashPower: {},
  }),
  getters: {
    getBackMenuList(): Menu[] {
      return this.backMenuList;
    },

    getDynamicAddedRoute(): boolean {
      return this.isDynamicAddedRoute;
    },

    getHashPower(): Recordable {
      return this.hashPower;
    },
  },
  actions: {
    setBackMenuList(list: Menu[]): void {
      this.backMenuList = list;
    },

    setDynamicAddedRoute(route: boolean): void {
      this.isDynamicAddedRoute = route;
    },
    resetState(): void {
      this.backMenuList = [];
      this.isDynamicAddedRoute = false;
    },

    async buildRoutes(query: SaaSUserMenuParams) {
      const { createMessage } = useMessage();
      const { t } = useI18n();
      const appStore = useAppSettingStoreWithOut();
      const token = getToken();

      let routes: AppRouteRecordRaw[] = [];
      const patchAffix = (routes: AppRouteRecordRaw[]) => {
        if (!routes || routes.length === 0) return;
        let pathNeedAffix: string =
          SaaSPageEnum.TENANT_HOMEPAGE || SaaSPageEnum.PLATFORM_HOEMPAGE || SaaSPageEnum.INSTANCE_PURCHASE;

        function patcher(routes: AppRouteRecordRaw[], parentPath = '') {
          if (parentPath) parentPath = parentPath + '/';
          routes.forEach((route: AppRouteRecordRaw) => {
            const { path, children, redirect } = route;
            const currentPath = path.startsWith('/') ? path : parentPath + path;
            if (currentPath === pathNeedAffix) {
              if (redirect) {
                pathNeedAffix = route.redirect! as string;
              } else {
                throw new Error('end');
              }
            }
            children && children.length > 0 && patcher(children, currentPath);
          });
        }

        try {
          patcher(routes);
        } catch (e) {
          // 已处理完毕跳出循环
        }
        return;
      };

      let routeList: AppRouteRecordRaw[] = [];

      try {
        let _routeList = (await getSaaSAccessibleMenu(query)) as AppRouteRecordRaw[];
        routeList = replaceList(_routeList);
        token &&
          createMessage.loading({
            content: t('sys.app.menuLoading'),
            duration: 1,
          });
      } catch (error) {
        console.error(error);
      }
      routeList = transformObjToRoute(routeList);

      const backMenuList = transformRouteToMenu(routeList);
      importFrontendRoutes(backMenuList, userInfoRoute);
      this.setBackMenuList(backMenuList);
      routeList = flatMultiLevelRoutes(routeList);
      routes = [PAGE_NOT_FOUND_ROUTE, ...routeList];

      patchAffix(routes);
      return routes;
    },

    async fetchUserInfo(loginInfo: SaaSLoginParams) {
      try {
        const userInfo = await loginSaaSApi({
          userName: loginInfo.userName,
          password: loginInfo.password,
          verificationCode: loginInfo.verificationCode,
        });
        const _tmp = parseUrl(userInfo.location);
        const saasUserStore = useUserStoreWithout();
        const userInfoWithToken = { ..._tmp, ...userInfo };
        saasUserStore.setUserInfo(userInfoWithToken);
        saasUserStore.setToken(userInfoWithToken.token);
        return userInfo;
      } catch (error) {
        console.log(error);
        throw error;
      }
    },

    async fetchHashPower() {
      const saasUserStore = useUserStoreWithout();
      const tenantCode = saasUserStore.getUserInfo.tenantCode as string;
      const userId = saasUserStore.getUserInfo.userId as string;
      const power = await getPermission({ tenantCode, userId });
      this.hashPower = hashPowerList(power);
    },
  },
});

export function usePermissionStoreWithOut() {
  return usePermissionStore(store);
}
